package com.me.jingdongshop.ui.fragment.goods;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flipboard.bottomsheet.BottomSheetLayout;
import com.me.common.base.BaseFragment;
import com.me.common.base.Const;
import com.me.common.base.Global;
import com.me.common.base.OttoBus;
import com.me.common.util.SharedPreUtil;
import com.me.jingdongshop.R;
import com.me.jingdongshop.model.bean.LocationList;
import com.me.jingdongshop.model.bean.Product;
import com.me.jingdongshop.model.protocol.IHttpService;
import com.me.jingdongshop.presenter.GoodsDetailPresenter;
import com.me.jingdongshop.presenter.TestFragmentPre;
import com.me.jingdongshop.ui.activity.BigImageActivity;
import com.me.jingdongshop.ui.activity.GoodsDetailActivity;
import com.me.jingdongshop.ui.activity.MainActivity;
import com.me.jingdongshop.ui.adapter.BottomAddressAdapter;
import com.me.jingdongshop.ui.view.GoodsItemView;
import com.squareup.otto.Subscribe;
import com.squareup.picasso.Picasso;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import static com.me.jingdongshop.R.id.goods_bottom_pro;
import static com.me.jingdongshop.R.id.goods_location;

/**
 * Created by YL on 2017/5/6.
 */

public class GoodsDetailGoodsFragment extends BaseFragment {

    private Product mProductDetail;
    //private com.daimajia.slider.library.SliderLayout detailF1Slider;
    private android.widget.TextView tvNewPrice;
    private android.widget.TextView tvOldPrice;
    private android.widget.RatingBar rbHomeRate;
    private android.widget.TextView goodsName;
    private android.widget.TextView goodsInventoryArea;
    private com.me.jingdongshop.ui.view.GoodsItemView goodsWhitePay;
    private com.me.jingdongshop.ui.view.GoodsItemView goodsCheck;
    private com.me.jingdongshop.ui.view.GoodsItemView goodsLocation;
    private android.support.v4.view.ViewPager goodsVp;
    private TextView goodsIndecator;
    private int mSize;
    private com.flipboard.bottomsheet.BottomSheetLayout bottomSheepLayout;
    private ImageView goodsBottomImg;
    private TextView goodsBottomPrice;
    private ImageView bottomBack;
    private android.widget.ImageButton goodsDown;
    private android.widget.ImageButton goodsUp;
    private TextView goodsBottomId;
    private com.zhy.view.flowlayout.TagFlowLayout flowlayout1;
    private com.zhy.view.flowlayout.TagFlowLayout flowlayout2;
    private EditText goodsCount;
    private Product.ProductBean mProduct;
    private List<String> mColors;
    private List<String> mSizes;
    private TextView goodsBottomAdd;
    private TextView goodsBottomBuy;
    private MyTagAdapter mMyTagAdapter;
    private MyTagAdapter mMyTagAdapter1;
    private String mSelectColor;
    private String mSelectSize;
    private android.widget.Button goodsAdd;
    private android.widget.RelativeLayout goodsComment;
    private android.widget.LinearLayout goodsBottomPro;
    private android.widget.LinearLayout goodsBottomCart;
    private ImageView bottomAddressBack;
    private android.support.v7.widget.RecyclerView bottomAddressRv;
    private List<LocationList.AddressListBean> mAddressList;
    private BottomAddressAdapter mAdapter;
    private View mCartPopLayout;
    private View mAddressPopLayout;
    private GoodsDetailPresenter pre = new GoodsDetailPresenter(this);
    private TestFragmentPre p = new TestFragmentPre(this);

    @Override
    public int getLayoutRes() {
        return R.layout.product_detail_f1;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        OttoBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OttoBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(Message msg) {
        if (msg.what == IHttpService.GOODS_ADDRESS_CODE) {
            String uid = SharedPreUtil.getString(Global.mContext, Const.KEY_UID, "");
            int id = mAdapter.mPo;
            p.getAddressDefault(uid, id);
            goodsLocation.setAddress((String) msg.obj);
            bottomSheepLayout.dismissSheet();
        }
    }

    @Override
    public void initView() {

        //detailF1Slider = (SliderLayout) mRoot.findViewById(R.id.detail_f1_slider);
        tvNewPrice = (TextView) mRoot.findViewById(R.id.tv_new_price);
        tvOldPrice = (TextView) mRoot.findViewById(R.id.tv_old_price);
        rbHomeRate = (RatingBar) mRoot.findViewById(R.id.rb_home_rate);
        goodsName = (TextView) mRoot.findViewById(R.id.goods_name);
        goodsInventoryArea = (TextView) mRoot.findViewById(R.id.goods_inventoryArea);
        goodsWhitePay = (GoodsItemView) mRoot.findViewById(R.id.goods_white_pay);
        goodsCheck = (GoodsItemView) mRoot.findViewById(R.id.goods_check);
        goodsLocation = (GoodsItemView) mRoot.findViewById(goods_location);
        goodsVp = (ViewPager) mRoot.findViewById(R.id.goods_vp);
        goodsIndecator = (TextView) mRoot.findViewById(R.id.goods_indecator);
        bottomSheepLayout = (BottomSheetLayout) mRoot.findViewById(R.id.bottom_sheep_layout);

        goodsBottomAdd = (TextView) mRoot.findViewById(R.id.goods_bottom_add);
        goodsBottomBuy = (TextView) mRoot.findViewById(R.id.goods_bottom_buy);
        goodsComment = (RelativeLayout) mRoot.findViewById(R.id.goods_comment);
        goodsBottomPro = (LinearLayout) mRoot.findViewById(goods_bottom_pro);
        goodsBottomCart = (LinearLayout) mRoot.findViewById(R.id.goods_bottom_cart);

    }

    @Override
    public void initListener() {
        goodsVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                goodsIndecator.setText((position + 1) + "/" + mSize);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        //加入购物车
        goodsCheck.setOnClickListener(this);
        goodsBottomAdd.setOnClickListener(this);
        //前往送货地址
        goodsLocation.setOnClickListener(this);
        goodsComment.setOnClickListener(this);
        //立即购买
        goodsBottomBuy.setOnClickListener(this);
        goodsBottomPro.setOnClickListener(this);
        goodsBottomCart.setOnClickListener(this);
    }

    @Override
    public void initData() {
        TestFragmentPre pre = new TestFragmentPre(this);
        //请求数据
        int id = getArguments().getInt("id", 1);
        pre.getProductData(id);
        String uid = SharedPreUtil.getString(Global.mContext, Const.KEY_UID, "");
        if (TextUtils.isEmpty(uid)) {
            return;
        }
        pre.getAddressList(uid);
    }

    /**
     * 展示界面数据
     */
    private void initShow() {
        mProduct = mProductDetail.getProduct();
        tvNewPrice.setText("￥" + mProduct.getPrice());
        tvOldPrice.setText("￥" + mProduct.getMarketPrice());
        //删除线
        tvOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        rbHomeRate.setRating(mProduct.getScore());
        goodsName.setText(mProduct.getName());
        goodsInventoryArea.setText("[配货]:" + mProduct.getInventoryArea());
        //头部商品图片的数量
        mSize = mProduct.getPics().size();
        goodsIndecator.setText("1/" + mSize);
        //初始化购物车
        initCartLayout();
    }

    /**
     * 顶部图片列表显示
     */
    private void initTopVP() {
        final List<String> pics = mProductDetail.getProduct().getPics();
        goodsVp.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return pics.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                ImageView imageView = new ImageView(container.getContext());
                Picasso.with(Global.mContext).load(IHttpService.HOST_URL + pics.get(position)).error(R.mipmap.ic_launcher).into(imageView);
                container.addView(imageView);

                //设置图片点击事件
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, BigImageActivity.class);
                        intent.putStringArrayListExtra("bigImg", (ArrayList<String>) mProduct.getBigPic());
                        intent.putExtra("position", position);
                        startActivity(intent);
                    }
                });
                return imageView;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        });

    }

    @Override
    public void onClick(View v, int id) {
        switch (id) {
            case R.id.goods_bottom_add:
            case R.id.goods_check:
                showOrHideCartLayout();
                break;
            case R.id.goods_add:
                //保存商品
                saveTocart();
                break;
            case R.id.goods_down:
                //减少商品数量
                cutCount();
                break;
            case R.id.goods_up:
                //增加商品数量
                addCount();
                break;
            case goods_location:
                if (isLogin()) {
                    showOrHideAddressList();
                }
                break;
            case R.id.goods_comment:
                GoodsDetailActivity goodsDetailActivity = (GoodsDetailActivity) getActivity();
                goodsDetailActivity.setToDetail();
                break;
            case R.id.goods_bottom_buy:
                isLogin();
                break;
            case R.id.goods_bottom_cart:
                Intent intent = new Intent(mActivity, MainActivity.class);
                intent.putExtra("key", 3);
                startActivity(intent);
                mActivity.finish();
                //发送otto事件，通知界面舒心
            /*    Message msg2 = new Message();
                msg2.what = Const.TOCART;
                msg2.obj = "3";
               OttoBus.getDefault().post(msg2);*/
                break;
            case goods_bottom_pro:
                Toast.makeText(mActivity, "收藏", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void showOrHideAddressList() {


        //设置点击显示和隐藏
        if (bottomSheepLayout.isSheetShowing()) {
            //显示-隐藏
            bottomSheepLayout.dismissSheet();
        } else {
            bottomSheepLayout.showWithSheetView(mAddressPopLayout);
        }
    }

    /**
     * @return 判断用户是否登录
     */
    private boolean isLogin() {
        String username = SharedPreUtil.getString(Global.mContext, Const.KEY_USERNAME, "");
        String uid = SharedPreUtil.getString(Global.mContext, Const.KEY_UID, "");
        if (TextUtils.isEmpty(username) && TextUtils.isEmpty(uid)) {
            Toast.makeText(mActivity, "请登录", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 加入购物车，将数据添加到内存和数据库
     */
    private void saveTocart() {

    }

    /**
     * 增加商品数量
     */
    private void addCount() {
        int s = Integer.parseInt(goodsCount.getText().toString());
        if (s == mProduct.getBuyLimit()) {
            Toast.makeText(mActivity, "商品购买数量达到上限", Toast.LENGTH_SHORT).show();
            return;
        }
        goodsCount.setText((s + 1) + "");
    }

    /**
     * 减一商品数量
     */
    private void cutCount() {
        int s = Integer.parseInt(goodsCount.getText().toString());
        if (s == 1) {
            return;
        }
        goodsCount.setText((s - 1) + "");
    }

    /**
     * 底部商品详情布局，显示或隐藏
     */
    private void showOrHideCartLayout() {
        //设置点击显示和隐藏
        if (bottomSheepLayout.isSheetShowing()) {
            //显示-隐藏
            bottomSheepLayout.dismissSheet();
        } else {
            bottomSheepLayout.showWithSheetView(mCartPopLayout);
        }
    }

    /**
     * 初始化购物车界面
     */
    private void initCartLayout() {
        mCartPopLayout = Global.inflate(R.layout.goods_out_bottom, bottomSheepLayout);
        goodsBottomImg = (ImageView) mCartPopLayout.findViewById(R.id.goods_bottom_img);
        goodsBottomPrice = (TextView) mCartPopLayout.findViewById(R.id.goods_bottom_price);
        bottomBack = (ImageView) mCartPopLayout.findViewById(R.id.bottom_back);
        goodsDown = (ImageButton) mCartPopLayout.findViewById(R.id.goods_down);
        goodsUp = (ImageButton) mCartPopLayout.findViewById(R.id.goods_up);
        goodsBottomId = (TextView) mCartPopLayout.findViewById(R.id.goods_bottom_id);
        flowlayout1 = (TagFlowLayout) mCartPopLayout.findViewById(R.id.flowlayout1);
        flowlayout2 = (TagFlowLayout) mCartPopLayout.findViewById(R.id.flowlayout2);
        goodsCount = (EditText) mCartPopLayout.findViewById(R.id.goods_count);
        goodsAdd = (Button) mCartPopLayout.findViewById(R.id.goods_add);

        bottomBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheepLayout.dismissSheet();
            }
        });
        //商品图标
        Picasso.with(Global.mContext).load(Const.HTTP_IMG + mProduct.getPics().get(0)).into(goodsBottomImg);
        //商品编号
        goodsBottomId.setText("商品编号:" + mProduct.getId());
        //保存属性的集合
        List<Product.ProductBean.ProductPropertyBean> productProperty = mProduct.getProductProperty();
        mColors = new ArrayList<>();
        mSizes = new ArrayList<>();
        //获得颜色，尺码的数据集合
        for (Product.ProductBean.ProductPropertyBean bean : productProperty) {
            if ("颜色".equals(bean.getK())) {
                mColors.add(bean.getV());
            } else if ("尺码".equals(bean.getK())) {
                mSizes.add(bean.getV());
            }
        }

        //初始化流布局
        initFlowlayout();
        //将商品加入购物车
        goodsAdd.setOnClickListener(this);
        goodsDown.setOnClickListener(this);
        goodsUp.setOnClickListener(this);
    }

    /**
     * 流布局
     */
    private void initFlowlayout() {
        //设置颜色和尺码的视图
        mMyTagAdapter = new MyTagAdapter(mColors);
        flowlayout1.setAdapter(mMyTagAdapter);
        mMyTagAdapter1 = new MyTagAdapter(mSizes);
        flowlayout2.setAdapter(mMyTagAdapter1);

        //设置参数最大点击数量
        flowlayout1.setMaxSelectCount(1);
        flowlayout1.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Toast.makeText(mActivity, "颜色：" + mColors.get(position), Toast.LENGTH_SHORT).show();
                mSelectColor = mColors.get(position);
                return true;
            }
        });
        flowlayout2.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Toast.makeText(mActivity, "尺码:" + mSizes.get(position), Toast.LENGTH_SHORT).show();
                mSelectSize = mSizes.get(position);
                return true;
            }
        });
    }

    @Override
    public void onHttpSuccess(int reqType, Message msg) {
        if (reqType == IHttpService.HTTP_PRODUCT) {
            mProductDetail = (Product) msg.obj;
            initTopVP();
            initShow();
        }
        if (reqType == IHttpService.HTTP_ADDRESS_LIST) {
            LocationList locationList = (LocationList) msg.obj;
            mAddressList = locationList.getAddressList();
            initAddress();
        }
        if (reqType == IHttpService.HTTP_ADDRESS_DEF) {
            mAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化地址
     */
    private void initAddress() {
        mAddressPopLayout = Global.inflate(R.layout.goods_out_location, bottomSheepLayout);
        bottomAddressBack = (ImageView) mAddressPopLayout.findViewById(R.id.bottom_address_back);
        bottomAddressRv = (RecyclerView) mAddressPopLayout.findViewById(R.id.bottom_aaddress_rv);
        //取消框框
        bottomAddressBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheepLayout.dismissSheet();
            }
        });
        //设置进来的时候默认地址
        String address = "";
        int po = -1;
        if (mAddressList != null && mAddressList.size() > 0) {
            LocationList.AddressListBean bean = pre.getDefaultAddress(mAddressList);
            address = bean.getProvince() + bean.getCity() + bean.getAddressArea() + bean.getAddressDetail();
            //改变ui的地址
            po = bean.getId();
        }
        goodsLocation.setAddress(address);
        //保存首次进入的id
        //适配器
        bottomAddressRv.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter = new BottomAddressAdapter(mActivity, mAddressList);
        mAdapter.mPo = po;
        bottomAddressRv.setAdapter(mAdapter);
    }

    @Override
    public void onHttpError(int reqType, String error) {

    }

    /**
     * 弹出窗中选项的流布局显示
     */
    private class MyTagAdapter extends TagAdapter<String> {
        private List<String> datas = new ArrayList<>();

        public MyTagAdapter(List<String> datas) {
            super(datas);
            this.datas = datas;
        }

        @Override
        public View getView(FlowLayout parent, int position, String s) {
            TextView textView = new TextView(getContext());
            textView.setText(datas.get(position));
            textView.setTextColor(getResources().getColor(R.color.goods_property_selector));
            //系统的方法
            int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 6, getResources().getDisplayMetrics());
            int textSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 4, getResources().getDisplayMetrics());
            //自己的工具类
            textView.setTextSize(textSize);
            textView.setPadding(padding, padding, padding, padding);

            textView.setBackgroundResource(R.drawable.goods_property_bg_selector);
            return textView;
        }

    }
}
